package com.bootdo.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientUtils {

    public static final String GET = "GET";
    public static final String POST = "POST";

    public static String sendGet(String path, String param) throws Exception {
        return send(path, param, GET);
    }

    public static String sendPost(String path, String param) throws Exception {
        return send(path, param, POST);
    }

    private static String send(String path, String param, String method) throws Exception {
        StringBuffer result = new StringBuffer();
        // 打开和URL之间的连接
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method); // GET、POST方法
        conn.setRequestProperty("Charset", "UTF-8");

        conn.connect();

        // 获取URLConnection对象对应的输出流
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        // 发送请求参数
        out.write(param);
        // flush输出流的缓冲
        out.flush();

        // 定义BufferedReader输入流来读取URL的响应
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }

        out.close();
        in.close();
        return result.toString();
    }
}
